/**
 * 修改岗位
 */
<template>
<vp-dialog ref="editDialogRef" :span="1">
	<template #title>
		<vp-label-add v-if="type === 'add'"/>
        <vp-label-edit v-else-if="type === 'edit'"/>
		<vp-label-view v-else/>
	</template>
	<el-form v-loading="loading" :model="formData" :rules="type === 'add' || type === 'edit' ? formRules : {}" ref="formRef" label-width="120px" :scroll-to-error="true">
		<el-row>
			<vp-col :span="1">
				<el-form-item prop="bh">
					<template #label><vp-label zh="岗位编号" en="Position No." align="left"/></template>
					<el-input v-if="type === 'add' || type === 'edit'" v-model="formData.bh" v-trim maxlength="100">
					</el-input>
					<span v-else>{{ formData.bh }}</span>
				</el-form-item>
			</vp-col>
			<vp-col :span="1">
				<el-form-item prop="mc">
					<template #label><vp-label zh="岗位名称" en="Position Name" align="left"/></template>
					<el-input v-if="type === 'add' || type === 'edit'"  v-model="formData.mc" v-trim maxlength="100"></el-input>
					<span v-else>{{ formData.mc }}</span>
				</el-form-item>
			</vp-col>
		</el-row>
	</el-form>
	<template #footer>
		<vp-btn-confirm v-if="type === 'add' || type === 'edit'" :loading="saveLoading" @click="handleSave"/>
	</template>
</vp-dialog>
</template>
<script setup lang="ts" name="editPosition">
import { ref } from 'vue'
import request from '/@/utils/request';
import validateUtils from '/@/utils/validateUtils';

	const emits = defineEmits(['formSubmited']);

	const formData = ref({
        id: "",
		bh: "",
		mc: "",
    });

	const formRules = {
        bh: [ validateUtils.notNull ],
		mc: [ validateUtils.notNull ],
    }

	const loading = ref(false);
    const saveLoading = ref(false);
    const type = ref('add');
	const editDialogRef = ref();
	const formRef = ref();

	// 打开弹窗
	const handleOpen = (__type: string, id: string) => {
		type.value = __type;
		initFormData();
		editDialogRef.value.handleOpen();
		if (__type === 'edit' || __type === 'view') {
			loading.value = true;
			request.get(`/training/position/${id}`).then((res) => {
				formData.value = {
					...formData.value,
					...res.data
				};
				loading.value = false;
			})
		}
	};

	// 清空数据
	const initFormData = () => {
		formData.value = {
			id: "",
			bh: "",
			mc: "",
		}
	}

	// 保存岗位信息
	const handleSave = () => {
		if (loading.value) {
			return;
		}
		saveLoading.value = true;
		formRef.value.validate((valid: Boolean) => {
			if (valid) {
				request.post("/training/position/save", {
					...formData.value
				}).then(() => {
					emits("formSubmited");
					editDialogRef.value.handleClose();
				}).catch(()=>{
                }).finally(()=>{
					saveLoading.value = false;
				})
			} else {
				saveLoading.value = false;
			}
		})
	}

	defineExpose({
        handleOpen,
    })
</script>
